<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--应用数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="moduleName"
            placeholder="请输入模块名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="moduleOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
            @check-change="handleCheckChange"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="登录账号" prop="userLogonname">
            <el-input
              v-model="queryParams.userLogonname"
              placeholder="请输入登录账号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" plain>搜索</el-button>
            <el-button type="info" icon="el-icon-refresh-left" size="mini" @click="resetQuery" plain>重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-circle-plus-outline"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:user:module:add']"
              plain>新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:user:module:edit']"
              plain>修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:user:module:remove']"
              plain>删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              icon="el-icon-upload"
              size="mini"
              @click="handleImport"
              v-hasPermi="['system:user:module:import']"
              plain>导入
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:user:module:export']"
              plain>导出
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-star-off"
              size="mini"
              :disabled="single"
              @click="handleGrant"
              v-hasPermi="['system:user:module:grant']"
              plain>授权
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="moduleList" :header-cell-style="{'text-align':'center'}" border
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column align="center" label="序号" type="index" width="50">
            <template scope="scope">
              <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="主键" align="center" prop="id" v-if="false"/>
          <el-table-column label="用户编号" align="center" prop="userId" v-if="false"/>
          <el-table-column label="模块编号" align="center" prop="moduleId" v-if="false"/>
          <el-table-column label="应用账号名称" align="center" prop="appUserDisplayname"/>
          <el-table-column label="应用登录名" align="center" prop="appUserLogonname"/>
          <el-table-column label="模块账号" align="center" prop="userLogonname"/>
          <el-table-column label="创建时间" align="center" prop="createTime">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
<!--          <el-table-column label="备注" align="center" prop="remark"/>-->
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

      </el-col>
    </el-row>
    <!-- 添加或修改模块用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-card class="box-card">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="应用账户名称" prop="appUserDisplayname">
                <el-input v-model="form.appUserDisplayname" placeholder="请输入应用账户名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="应用登录名" prop="appUserLogonname">
                <el-input v-model="form.appUserLogonname" placeholder="请输入应用登录名"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="应用账户密码" prop="appUserPassword">
                <el-input v-model="form.appUserPassword" placeholder="请输入应用账户密码"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="模块SSO账号" prop="userLogonname">
                <el-input v-model="form.userLogonname" placeholder="请输入模块登录账号"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="模块SSO密码" prop="userPassword">
                <el-input v-model="form.userPassword" placeholder="请输入登录密码"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-success" type="success" @click="submitForm" plain>确 定</el-button>
        <el-button icon="el-icon-error" type="danger" @click="cancel" plain>取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户授权对话框 -->
    <el-dialog title="用户授权" :visible.sync="openGrant" width="800px" append-to-body>
      <el-card class="box-card">
        <el-form ref="formGrant" :model="formGrant" :rules="rulesGrant" label-width="120px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="应用账户名称" prop="appUserDisplayname">
                <el-input v-model="formGrant.userId" v-show="false"></el-input>
                <el-input v-model="formGrant.moduleId" v-show="false"></el-input>
                <el-input v-model="formGrant.appUserDisplayname" disabled placeholder="请输入应用账户名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="应用登录名" prop="appUserLogonname">
                <el-input v-model="formGrant.appUserLogonname" disabled placeholder="请输入应用登录名"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="应用账户密码" prop="appUserPassword">
                <el-input v-model="formGrant.appUserPassword" disabled placeholder="请输入应用账户密码"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="模块SSO账号" prop="userLogonname">
                <el-input v-model="formGrant.userLogonname" placeholder="请输入模块登录账号"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="模块SSO密码" prop="userPassword">
                <el-input v-model="formGrant.userPassword" placeholder="请输入登录密码"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="formGrant.remark" placeholder="请输入备注"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-table ref="grantTable" v-loading="grantLoading" :data="grantModuleList"
                  :header-cell-style="{'text-align':'center'}" border>
          <el-table-column align="center" type="selection" width="55"/>
          <el-table-column align="center" label="序号" type="index" width="50">
            <template scope="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="false" align="center" label="模块编号" prop="moduleId"/>
          <el-table-column align="left" label="模块名称" prop="moduleName"/>
          <el-table-column align="left" label="模块简称" prop="moduleShortName"/>
          <el-table-column align="left" label="英文简称" prop="moduleShortNameEn"/>
          <!--          <el-table-column align="left" label="模块地址" prop="moduleAddress"/>-->
          <!--          <el-table-column align="left" label="端口" prop="modulePort"/>-->
          <!--          <el-table-column align="left" label="单点登录地址" prop="moduleSsoAddress"/>-->
          <!--          <el-table-column align="left" label="待办服务地址" prop="moduleTodoAddress"/>-->
          <el-table-column align="center" label="编号" prop="no"/>
          <!--          <el-table-column align="left" label="备注" prop="remark"/>-->
        </el-table>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-success" type="success" @click="submitGrantForm" plain>确 定</el-button>
        <el-button icon="el-icon-error" type="danger" @click="openGrant=false;" plain>取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url+'?moduleId='+queryParams.moduleId"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-button type="primary" size="mini" @click="downloadTemplate">下载模板</el-button>&nbsp;&nbsp;
          <el-tag type="danger">仅支持“xls”或“xlsx”格式文件！</el-tag>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-success" type="success" @click="submitFileForm" plain>确 定</el-button>
        <el-button icon="el-icon-error" type="danger" @click="upload.open = false" plain>取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUserModule,
  getUserModule,
  delUserModule,
  addUserModule,
  updateUserModule,
  exportUserModule, addGrantUserModule, downloadTemplate
} from "@/api/module/biz_user_module";

import {listGrantModule, listModule} from "@/api/module/biz_module";
import {decrypt, encrypt} from "@/utils/jsencrypt";
import {getToken} from "@/utils/auth";

export default {
  name: "Module",
  data() {
    return {
      // 遮罩层
      loading: true,
      //授权模块遮罩
      grantLoading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 模块用户表格数据
      moduleList: [],
      //授权模块数据
      grantModuleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //是否显示授权对话框
      openGrant: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 'um.create_time',
        isAsc: 'asc',
        moduleId: null,
        userLogonname: null
      },
      // 表单参数
      form: {},
      //授权表单
      formGrant: {},
      // 表单校验
      rules: {
        appUserDisplayname: [
          {required: true, message: "应用账户名称不能为空", trigger: "blur"}
        ],
        appUserLogonname: [
          {required: true, message: "应用登录名不能为空", trigger: "blur"}
        ],
        appUserPassword: [
          {required: true, message: "应用登录密码不能为空", trigger: "blur"}
        ],
        userLogonname: [
          {required: true, message: "用户所在模块登录账号不能为空", trigger: "blur"}
        ],
        userPassword: [
          {required: true, message: "用户所在模块登录密码不能为空", trigger: "blur"}
        ]
      },
      //授权表单验证
      rulesGrant: {
        appUserDisplayname: [
          {required: true, message: "应用账户名称不能为空", trigger: "blur"}
        ],
        appUserLogonname: [
          {required: true, message: "应用登录名不能为空", trigger: "blur"}
        ],
        appUserPassword: [
          {required: true, message: "应用登录密码不能为空", trigger: "blur"}
        ],
        userLogonname: [
          {required: true, message: "用户所在模块登录账号不能为空", trigger: "blur"}
        ],
        userPassword: [
          {required: true, message: "用户所在模块登录密码不能为空", trigger: "blur"}
        ]
      },
      //模块名称
      moduleName: null,
      // 部门树选项
      moduleOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      //选中模块
      moduleTitle: null,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/module/importData"
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    moduleName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.initModulesTree();
  },
  methods: {
    /** 查询模块用户列表 */
    getList() {
      this.loading = true;
      listUserModule(this.queryParams).then(response => {
        this.moduleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    initModulesTree() {
      listModule().then(response => {
        let array = new Array();
        response.rows.forEach(function (item, index) {
          //item 就是当日按循环到的对象
          //index是循环的索引，从0开始
          array.push({id: item.moduleId, label: item.moduleName, children: null});
        });
        this.moduleOptions = array;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.moduleId = data.id;
      this.moduleTitle = data.label;
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        moduleId: null,
        appUserDisplayname: null,
        appUserLogonname: null,
        appUserPassword: null,
        userLogonname: null,
        userPassword: null,
        remark: null,
        isDel: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (!this.queryParams.moduleId) {
        this.msgError("请选择应用模块！");
        return;
      }
      this.reset();
      this.open = true;
      this.title = "添加" + (this.moduleTitle != null ? "【" + this.moduleTitle + "】" : "") + "模块用户";
      this.form.moduleId = this.queryParams.moduleId;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getUserModule(id).then(response => {
        response.data.appUserPassword = decrypt(response.data.appUserPassword);
        response.data.userPassword = decrypt(response.data.userPassword);
        this.form = response.data;
        this.open = true;
        this.title = "修改" + (this.moduleTitle != null ? "【" + this.moduleTitle + "】" : "") + "模块用户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.userPassword = encrypt(this.form.userPassword);
          this.form.appUserPassword = encrypt(this.form.appUserPassword);
          if (this.form.id != null) {
            updateUserModule(this.form).then(response => {
              if (response.code == 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.form.userPassword = decrypt(this.form.userPassword);
                this.form.appUserPassword = decrypt(this.form.appUserPassword);
                this.msgError(response.msg);
              }
            });
          } else {
            addUserModule(this.form).then(response => {
              if (response.code == 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.form.userPassword = decrypt(this.form.userPassword);
                this.form.appUserPassword = decrypt(this.form.appUserPassword);
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    //授权按钮事件
    handleGrant: function (row) {
      this.resetForm("formGrant");
      const id = row.id || this.ids
      getUserModule(id).then(response => {
        this.formGrant.userId = response.data.userId;
        this.formGrant.appUserDisplayname = response.data.appUserDisplayname;
        this.formGrant.appUserLogonname = response.data.appUserLogonname;
        this.formGrant.appUserPassword = response.data.appUserPassword;
        this.openGrant = true;
        listGrantModule(response.data.userId).then(response => {
          this.grantModuleList = response.rows;
          this.grantLoading = false;
        });
      });
    },
    /** 提交授权信息 */
    submitGrantForm: function () {
      this.$refs["formGrant"].validate(valid => {
        if (valid) {
          const rows = this.$refs.grantTable.selection;
          if (rows.length == 0 || rows.length > 1) {
            this.msgError("请选择一个模块！");
            return;
          }
          this.formGrant.moduleId = rows[0].moduleId;
          this.formGrant.userPassword = encrypt(this.formGrant.userPassword);
          addGrantUserModule(this.formGrant).then(response => {
            if (response.code == 200) {
              this.msgSuccess("新增成功");
              this.openGrant = false;
              this.getList();
            } else {
              this.formGrant.userPassword = decrypt(this.formGrant.userPassword);
              this.msgError(response.msg);
            }
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delUserModule(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      exportUserModule(queryParams).then(response => {
        this.download(response.msg);
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      if (!this.queryParams.moduleId) {
        this.msgError("请选择应用模块！");
        return;
      }
      this.upload.title = "模块用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    downloadTemplate() {
      downloadTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.upload.isUploading = true;
      this.$refs.upload.submit();
    }
  }
};
</script>
<style>
.el-tree-node.is-current > .el-tree-node__content {
  background-color: #2F8DFB !important;
  color: white;
}

.el-checkbox__input.is-checked + .el-checkbox__label {
  color: black;
}
</style>
